package com.tanhua.app.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.exceptions.ClientException;
import com.tanhua.api.db.UserApi;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.FriendApi;
import com.tanhua.api.mongo.RecommendUserApi;
import com.tanhua.api.mongo.UserLikeApi;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.mongo.Visitors;
import com.tanhua.domain.vo.*;
import com.tanhua.template.AipFaceTemplate;
import com.tanhua.template.HuanXinTemplate;
import com.tanhua.template.OssTemplate;
import com.tanhua.template.SmSTemplate;
import com.tanhua.utils.JwtUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Reference
    private UserApi userApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private SmSTemplate smSTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;



    public ResponseEntity saveUser(@RequestBody User user){
        long id = userApi.saveUser(user);
        return ResponseEntity.ok(id);
    }

    public ResponseEntity findByPhone(String phone){
        User user = userApi.findByPhone(phone);
        return ResponseEntity.ok(user);
    }

    //实现发短信流程
    public ResponseEntity login(String phone) throws ClientException {
        // 1 生成6位随机数
        String code = RandomUtil.randomNumbers(6);
        //测试阶段 统一用123456
        code="123456";
        // 2 发送短信
        //smSTemplate.sendSms(phone,code);
        //3 将验证码存入redis中（有时效性）
        stringRedisTemplate.opsForValue().set("SMS_CODE_"+phone,code,10, TimeUnit.MINUTES);

        return ResponseEntity.ok(null); //返回的是空数据
    }

    //注册登录
    public ResponseEntity loginVerification(String phone, String vCode) {

        // 1 判断页面给的验证码是否和redis中的验证码一致
        String code = stringRedisTemplate.opsForValue().get("SMS_CODE_" + phone);
        if(!StrUtil.equals(vCode,code)){
            // 不一致 --结束程序直接返回验证码错误
            return ResponseEntity.status(500).body("验证码错误");
        }

        // 验证码匹配成功 删除redis中的验证码
        stringRedisTemplate.delete("SMS_CODE_"+phone);

        //定义用户是否存在的标识
        Boolean isNew=false;
        // 2 验证码一致，根据手机号查询该用户是否存在
        User user = userApi.findByPhone(phone);
        if(user==null){
            // 不存在 -- 将该用户保存到数据库中（代表是个新用户） 返回isNew=true
            user = new User();
            user.setPhone(phone);
            user.setPassword(SecureUtil.md5("123456"));
            long id = userApi.saveUser(user); //注册到探花的数据库
            user.setId(id);
            //代表是新用户
            isNew=true;

            //注册到环信上即可
            huanXinTemplate.register(user.getId()); //每一个探花的新用户都注册到环信上了

        }

        // 将该用户（新/老）的对象和token绑定放入redis中
        String token = JwtUtil.createToken(phone, user.getId(), "tanhua");
        //将token做为key 用户作为value放入redis中
        String user_json = JSON.toJSONString(user);
        stringRedisTemplate.opsForValue().set("TOKEN_"+token,user_json,1,TimeUnit.DAYS);

        //返回结果
        Map resultMap=new HashMap();
        resultMap.put("token",token); //jwt的框架来优化
        resultMap.put("isNew",isNew);

        //将一些数据放入消息中间件中  让消费者拿着需要的数据插入到数据库中
                    //Map  1：当前用户的id 2 type=0101/0102  3 当前时间
        Map logMap=new HashMap<>();
        logMap.put("userId",user.getId());
        logMap.put("type",isNew?"0102":"0101");
        logMap.put("logTime",new DateTime().toString("yyyy-MM-dd"));
        rocketMQTemplate.convertAndSend("tanhua-logs",logMap);
        System.out.println("消息中间件中发送数据了...");

        return ResponseEntity.ok(resultMap);
    }

    //完善新用户的个人信息保存
    public ResponseEntity loginReginfo(UserInfo userInfo) {
        //1 根据token从redis中获取User用户
        User user = UserHolder.getUser();
        //2 设置UserInfo的id就是User用户的id
        userInfo.setId(user.getId());
        //3 保存userinfo到数据库（没有图片的oss地址）
        userInfoApi.save(userInfo);
        return ResponseEntity.ok(null);


    }
    // 根据token从redis中获取用户
    public User tokenfromUser(String token) {
        String json = stringRedisTemplate.opsForValue().get("TOKEN_" + token);
        //将json转换成对象
        User user = JSON.parseObject(json, User.class);
        //追加一天
        stringRedisTemplate.opsForValue().set("TOKEN_"+token,json,1,TimeUnit.DAYS);
        return user;
    }

    //更新新用户个人完善信息的头像
    public ResponseEntity loginReginfoPic(MultipartFile headPhoto, String token) throws IOException {

        // 检测是否给的是人脸图片
        boolean flg = aipFaceTemplate.detect(headPhoto.getBytes());
        System.out.println("人脸扫描的结果:"+flg);
        if(!flg){
            //不是人脸
            return ResponseEntity.status(500).body("人脸验证失败");
        }
        // 将人脸图片上传到阿里oss云存储
        String url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        // 记录地址 更新userinfo的图片地址数据
        UserInfo userInfo = new UserInfo();
        userInfo.setAvatar(url);
        userInfo.setCoverPic(url);
        User user = tokenfromUser(token);
        userInfo.setId(user.getId());

        userInfoApi.update(userInfo);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity findUserInfoVo(Long userID) {
        UserInfo userInfo=userInfoApi.findUserInfoVo(userID);
        //将UserInfo的数据给UserInfoVo
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        //string类型age
        if(userInfo.getAge()!=null){
            userInfoVo.setAge(userInfo.getAge().toString());
        }

        return ResponseEntity.ok(userInfoVo);
    }

    //修改我的信息
    public ResponseEntity updateUserInfo(UserInfo userInfo, String token) {
        // 根据token获取user的id(userInfo的id一致)
        User user = tokenfromUser(token);
        // 给userInfo绑定id
        userInfo.setId(user.getId());
        // 修改userInfo数据
        userInfoApi.update(userInfo);
        return ResponseEntity.ok(null);
    }

    @Reference
    private UserLikeApi userLikeApi;
    @Reference
    private RecommendUserApi recommendUserApi;

    //互相喜欢，喜欢，粉丝 - 统计
    public ResponseEntity counts() {

        //获取当前登录用户的id
        Long userId = UserHolder.getUser().getId();

        //1 互相喜欢的数量
        Long eachLoveCount=userLikeApi.findeachLoveCount(userId);
        //2 喜欢对方的数量
        Long loveCount=userLikeApi.findloveCount(userId);
        //3 对方喜欢你的数量
        Long fanCount=userLikeApi.findfanCount(userId);
        //4 封装并返回
        CountsVo countsVo = new CountsVo(eachLoveCount,loveCount,fanCount);

        return ResponseEntity.ok(countsVo);

    }

    //互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
    public ResponseEntity findMyCount(Integer page, Integer pagesize, Integer type) {

        PageBeanVo vo=null;
        List<UserLikeListVo> userLikeListVoList=new ArrayList();
        // 1 对type做switch判断
        switch (type){
            case 1:{
                //查询互相喜欢 tanhua_friends
                vo=userLikeApi.findeachLoveList(page,pagesize,UserHolder.getUser().getId());
                List<Friend> items = (List<Friend>) vo.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (Friend item : items) {
                        UserInfo userInfo = userInfoApi.findUserInfoVo(item.getFriendId());
                        UserLikeListVo userLikeListVo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo,userLikeListVo);
                        Long score = recommendUserApi.findScore(UserHolder.getUser().getId(), item.getFriendId());
                        userLikeListVo.setMatchRate(score.intValue()); //缘分值
                        userLikeListVoList.add(userLikeListVo);
                    }
                }
                break;
            }
            case 2:{
                //查询当前登录者喜欢的用户 user_like
                vo=userLikeApi.findloveList(page,pagesize,UserHolder.getUser().getId());
                List<UserLike> items = (List<UserLike>) vo.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (UserLike item : items) {
                        UserInfo userInfo = userInfoApi.findUserInfoVo(item.getLikeUserId());
                        UserLikeListVo userLikeListVo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo,userLikeListVo);
                        Long score = recommendUserApi.findScore(UserHolder.getUser().getId(), item.getLikeUserId());
                        userLikeListVo.setMatchRate(score.intValue()); //缘分值
                        userLikeListVoList.add(userLikeListVo);
                    }
                }
                break;
            }
            case 3:{
                //查询当前喜欢我的用户 user_like
                vo=userLikeApi.findfanList(page,pagesize,UserHolder.getUser().getId());
                List<UserLike> items = (List<UserLike>) vo.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (UserLike item : items) {
                        UserInfo userInfo = userInfoApi.findUserInfoVo(item.getUserId());
                        UserLikeListVo userLikeListVo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo,userLikeListVo);
                        Long score = recommendUserApi.findScore(UserHolder.getUser().getId(), item.getUserId());
                        userLikeListVo.setMatchRate(score.intValue()); //缘分值
                        userLikeListVoList.add(userLikeListVo);
                    }
                }
                break;
            }
            case 4:{
                //查询历史访问记录用户 visitors
                vo=userLikeApi.findHistory(page,pagesize,UserHolder.getUser().getId());
                List<Visitors> items = (List<Visitors>) vo.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (Visitors item : items) {
                        UserInfo userInfo = userInfoApi.findUserInfoVo(item.getVisitorUserId());
                        UserLikeListVo userLikeListVo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo,userLikeListVo);
                        Long score = recommendUserApi.findScore(UserHolder.getUser().getId(), item.getVisitorUserId());
                        userLikeListVo.setMatchRate(score.intValue()); //缘分值
                        userLikeListVoList.add(userLikeListVo);
                    }
                }
                break;
            }
        }

        //3 封装app需要的UserLikeListVo
        vo.setItems(userLikeListVoList);
        //4 将UserLikeListVo封装给分页进行返回
        return ResponseEntity.ok(vo);
    }

    @Reference
    private FriendApi friendApi;

    //粉丝变朋友
    public ResponseEntity fansToFriend(Long fansId) {

        // 1 tanhua_friends添加2条数据
        friendApi.contacts(UserHolder.getUser().getId(),fansId);
        //2 user_like删除粉丝的数据
        userLikeApi.delete(UserHolder.getUser().getId(),fansId);

        return ResponseEntity.ok(null);

    }

    //取消喜欢
    public ResponseEntity removeLike(Long uid) {

        //1 判断是从互相喜欢取消的还是从喜欢中取消的
        boolean flg=friendApi.isFriend(UserHolder.getUser().getId(),uid);
        if(flg){
            //2 互相喜欢取消--tanhua_friends删除2条数据 user_like添加回粉丝
            friendApi.deleteFriend(UserHolder.getUser().getId(),uid);
            userLikeApi.save(UserHolder.getUser().getId(),uid);
        }else{
            //3 喜欢中取消--user_like 将喜欢的人删除掉
            userLikeApi.delete(uid,UserHolder.getUser().getId());
        }

        return ResponseEntity.ok(null);
    }

//    探花-左滑右滑
    public ResponseEntity cards() {
        Long userId = UserHolder.getUser().getId();
//        查询userinfo表 不要登录用户
        List<UserInfo> infoButUser = userInfoApi.findInfoButUser(userId);
        List<CardsVo> cardsVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(infoButUser)){
            for (UserInfo userInfo : infoButUser) {
//                  查询和登录用户互相喜欢的
                if(friendApi.isFriend(userId,userInfo.getId())){
                    continue;
                }
//                是否是登录用户喜欢的
                if (userLikeApi.isFanForUser(userId,userInfo.getId())){
                    continue;
                }
                CardsVo cardsVo = new CardsVo();
                BeanUtil.copyProperties(userInfo,cardsVo);
                cardsVo.setTags(userInfo.getTags().split(","));
                cardsVoList.add(cardsVo);
            }
        }
//        返回
        return ResponseEntity.ok(cardsVoList);
    }

//    探花-喜欢
    public ResponseEntity love(Long cardUserId) {
        Long userId  = UserHolder.getUser().getId();
//        判断卡片用户是否喜欢登录用户
        boolean fanForUser = userLikeApi.isFanForUser(cardUserId,userId);
        if (fanForUser){
//            添加到朋友
            friendApi.contacts(cardUserId,userId);
            //2 user_like删除粉丝的数据
            userLikeApi.delete(userId,cardUserId);

        }else {
            userLikeApi.save(cardUserId,userId);
        }
        return ResponseEntity.ok(null);
    }

//    探花-不喜欢
    public ResponseEntity unlove(Long cardUserId) {
//        Long userId = UserHolder.getUser().getId();
//        userLikeApi.delete(cardUserId,userId);
        return ResponseEntity.ok(null);
    }
}
